package com.rover.controller.system;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.grid.Page;
import com.rover.entity.system.CodeValue;
import com.rover.service.system.CodeValueService;
import com.utils.AppUtil;

/**
 * 用户
 */
@Controller
@RequestMapping("/codeValueController")
public class CodeValueController {

	@Autowired
	private CodeValueService codeValueService;
	
	
	
	// 用户管理
	@RequestMapping("/query")
	@ResponseBody
	public Map<String, Object> query(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> params = new HashMap<String, Object>();
		String codeId = request.getParameter("codeId");
		String codeValueName = request.getParameter("name");
		String hql = " where 1=1";
		if (null != codeId) {
			hql += " and cv.code.id=" + codeId ;
		}
		if(null != codeValueName && !codeValueName.isEmpty()){
			
			hql = hql + " and cv.itemText like :itemText";
			params.put("itemText", "%" + codeValueName + "%");
		}
		String treeCode = request.getParameter("treeCode");
    	if(StringUtils.isNotBlank(treeCode)){
    		hql += " and treeCode like:treeCode and treeCode<>:treeCode2";	
    		params.put("treeCode", treeCode + "%");
    		params.put("treeCode2", treeCode );
    	}
		Page<CodeValue> page = new Page<CodeValue>(request);
		page = codeValueService.query(page, hql, params);
		map = AppUtil.buildJSONDataResponse(page.getResult(),
				page.getTotalCount());
		return map;
	}
	// 用户管理
	@RequestMapping("/queryTree")
	@ResponseBody
	public Map<String, Object> queryTree(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> params = new HashMap<String, Object>();
		String codeId = request.getParameter("codeId");
		String hql = " where 1=1";
		if (null != codeId) {
			hql += " and cv.code.id=" + codeId ;
		}
		
		String treeCode = request.getParameter("treeCode");
    	if(StringUtils.isNotBlank(treeCode)){
    		hql += " and treeCode like:treeCode and treeCode<>:treeCode2";	
    		params.put("treeCode", treeCode + "%");
    		params.put("treeCode2", treeCode );
    	}
    	else
    		hql += " and length(treeCode)=3 ";	
		Page<CodeValue> page = new Page<CodeValue>(request);
		page = codeValueService.query(page, hql, params);
		map = AppUtil.buildJSONDataResponse(page.getResult(),
				page.getTotalCount());
		return map;
	}
	
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> save(CodeValue codeValue, HttpServletRequest request)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Boolean success = true;
		String message = "";
		try {
			String codeId=	request.getParameter("codeId");
			if(codeValueService.isItemTextRepeat(codeValue,Long.valueOf(codeId))){
				success=false;
				message = "此编码名称已存在，请重新输入！";
			}else if(codeValueService.isItemValueRepeat(codeValue,Long.valueOf(codeId))){
				success=false;
				message = "此编码值已存在，请重新输入！";
			}
			else
			   codeValueService.save(codeValue,codeId);
			map.put("success", success);
			map.put("message", message);
		} catch (Exception e) {
			map.put("success", false);
			map.put("message", e.getMessage());
		}
		return map;
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> delete(@RequestParam("id") String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		// String id = request.getParameter("id");
		try {
			codeValueService.delete(Long.valueOf(id));
			map.put("success", true);
			map.put("message", "");

		} catch (Exception e) {
			map.put("success", false);
			map.put("message", e.getMessage());
		}
		return map;
	}
	
	@RequestMapping(value = "/treeSave", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> treeSave(CodeValue codeValue, HttpServletRequest request)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Boolean success = true;
		String message = "";
		try {
			String codeId=	request.getParameter("codeId");
			
				if(codeValueService.isItemTextRepeat(codeValue,Long.valueOf(codeId))){
					success=false;
					message = "此编码名称已存在，请重新输入！";
				}else if(codeValueService.isItemValueRepeat(codeValue,Long.valueOf(codeId))){
					success=false;
					message = "此编码值已存在，请重新输入！";
				}
				else{
					if(codeValue.getId()==null)
				       codeValueService.treeSave(codeValue,codeId);
					else{
						codeValueService.treeUpdate(codeValue, codeId);
					}
				}
			
			map.put("success", success);
			map.put("message", message);
		} catch (Exception e) {
			// logger.error(e.getMessage(), e);
			map.put("success", false);
			map.put("message", e.getMessage());
		}
		return map;
	}
	
	
	@RequestMapping(value = "/getCodeValue", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> getCodeValue(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map.put("success", true);
			map.put("data",codeValueService.getCodeValue(request.getParameter("codeName")));
		} catch (Exception e) {
			map.put("success", false);
			map.put("data", e.getMessage());
		}
		return map;
	}
	/*
	 * 根据codeId获取treeCode的json数据
	 * @idType  id的值是itenValue还是treeCode
	 * */
	@RequestMapping("/treeJsonId")
	@ResponseBody
	public void treeJsonId(HttpServletRequest request,HttpServletResponse response) throws IOException {
		List<CodeValue> li= codeValueService.getTreeList(Long.valueOf( request.getParameter("codeId")));
	    String str=	json(li,request.getParameter("idType"));
		 response.setContentType("application/json;charset=UTF-8");
	        PrintWriter out = response.getWriter();
	        out.write(str);
	}
	/*
	 * 获取treeCode的json数据
	 * @idType  id的值是itenValue还是treeCode
	 * */
	@RequestMapping("/treeJsonName")
	@ResponseBody
	public void treeJsonName(HttpServletRequest request,HttpServletResponse response) throws IOException {
		List<CodeValue> li= codeValueService.getTreeList(request.getParameter("codeName"));
		
	    String str=	json(li,request.getParameter("idType"));
		 response.setContentType("application/json;charset=UTF-8");
	        PrintWriter out = response.getWriter();
	        out.write(str);
	}
	private String json(List<?> li,String idType) {
		StringBuilder db=new StringBuilder();
		db.append("[");
		for(int i=0;i<li.size();i++){
			CodeValue codeValue=(CodeValue)li.get(i);
			String strTemp="";
			if(codeValue.getCodeValues().size()>0){
				strTemp=" ,\"leaf\": \"false\" ,\"children\": "+json(Arrays.asList(codeValue.getCodeValues().toArray()),idType);
			}
			else
			{
				strTemp=" ,\"leaf\": \"true\" ";
			}
			String id="";
			if(idType.equals("itenValue")){
				id=codeValue.getItemValue();
			}
			else
				id=codeValue.getTreeCode();
			if((li.size()-1)==i){
				  db.append("{\"text\": \""+codeValue.getItemText()+"\",\"id\":\""+id+"\",\"treeCode\":\""+codeValue.getTreeCode()+"\""+strTemp+"}");
			}
			else{
				  db.append("{\"text\": \""+codeValue.getItemText()+"\",\"id\":\""+id+"\",\"treeCode\":\""+codeValue.getTreeCode()+"\""+strTemp+"},");
			}
		}
		db.append(" ]");
		return db.toString();
	}
    
	
}
